package test.framework.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 当前后台系统数据源配置
 * @author: huwei
 * @date:   2020/1/14 10:44
 * @version:  1.0.0
*/
@Configuration
@MapperScan(basePackages = "test.**.user.mapper", sqlSessionFactoryRef = "datasource1SqlSessionFactory")
public class DataSource1Config {

    @Resource
    private DataSourceCommonConfig dataSourceCommonConfig;

    @Primary
    @Bean(name = "datasource1")
    @ConfigurationProperties(prefix = "spring.datasource.datasource1")
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "datasource1SqlSessionFactory")
    public MybatisSqlSessionFactoryBean datasource1SqlSessionFactory(@Qualifier("datasource1") DataSource datasource)
            throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:test/module/user/**/*.xml"));
        bean.setPlugins(dataSourceCommonConfig.paginationInterceptor());
        return bean;
    }
}